package org.bees.cms.service.bean;

import java.util.List;

import javax.persistence.EntityManager;

import org.bees.cms.common.jpql.CriterionFactory;
import org.bees.cms.common.jpql.SimpleJPQL;
import org.bees.cms.core.Named;
import org.bees.cms.service.NamedService;

public abstract class NamedServiceSupport<T extends Named> implements NamedService<T> {

	@Override
	public T findByName(String name) throws Exception {
		List<T> entities = listByName(name);
		return entities == null ? null : entities.isEmpty() ? null : entities.get(0);
	}

	@Override
	public List<T> listByName(String name) throws Exception {
		SimpleJPQL jpql = new SimpleJPQL(parameter());
		CriterionFactory factory = jpql.getCriterionFactory();
		jpql.where().add(factory.equal("name", name));
		List<T> entities = jpql.multiple(manager(), parameter());
		return entities;
	}

	protected abstract EntityManager manager();

	protected abstract Class<T> parameter();

}
